package com.easyexcle.demo.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.easyexcle.demo.listener.UserListener;
import com.easyexcle.demo.pojo.User;
import com.easyexcle.demo.utils.Column;
import com.easyexcle.demo.utils.ExcelTool;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.easyexcle.demo.easyExcel.util.ExcelUtil.writeExcelWithModel;

@RestController
public class ExcleController {

    /**
     * 学习网址；https://www.yuque.com/easyexcel/doc/read
     * 参考网站：https://www.jianshu.com/p/cfa6aa5c9329
     */

    @Resource
    private UserListener userListener;


    @GetMapping("test")
    public String test(){
        return "test ok";
    }

    /**
     * 直接下载 没有设置样式
     * @param response
     * @throws IOException
     */
    @GetMapping("download")
    public void downExcle(HttpServletResponse response) throws IOException {

        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 防止中文乱码
        String fileName = URLEncoder.encode("测试下载", "UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + fileName + ".xlsx");

        //响应的输入流
        ServletOutputStream outputStream = response.getOutputStream();

        // workbook
        ExcelWriterBuilder writeWorkBook = EasyExcel.write(outputStream, User.class);

        // sheet
        writeWorkBook.sheet().doWrite(initData());

    }

    /**
     * 测试模板类型 导出
     */
    @GetMapping("down2")
    public void downTest() throws FileNotFoundException {
        OutputStream outputStream = null;
        //指定位置
        outputStream = new FileOutputStream(new File("D:\\模板导出.xls"));
        String sheetName = "导出文件";
        writeExcelWithModel(outputStream, sheetName, initData(), User.class);
    }

    // 上传
    @RequestMapping("upload")
    @ResponseBody
    public String upload(MultipartFile excelFile) throws IOException {

        try {
            // 构建一个工作簿对象
            ExcelReaderBuilder readWorkBook = EasyExcel.read(excelFile.getInputStream(),
                    User.class, userListener);

            // 获取他的工作表 & 读
            readWorkBook.sheet().doRead();
            return "success";

        } catch (IOException e) {
            e.printStackTrace();
            return "fail";
        }
    }


    @GetMapping("/getFileBase64")
    public String getFileBase64() throws IOException {
        byte[] bytes=null;
        String base64String=null;
        //InputStream inputStream=null;

        File file=new File("http://36.152.29.162:50206/home/hlms/upload/718/report/202109/日度汇报2021-9-27_测试44(1).docx");
        FileInputStream fileInputStream=new FileInputStream(file);
        int size=fileInputStream.available();
        bytes=new byte[size];
        fileInputStream.read(bytes);
        fileInputStream.close();

        BASE64Encoder encoder=new BASE64Encoder();
        base64String=encoder.encode(bytes);

        return base64String;
    }


    private List<User> initData(){
        List<User> list=new ArrayList<>();
        for(int i=0;i<=5;i++){
            User u=new User();
            u.setUser(i);
            u.setName("张"+i);
            u.setAge(i);
            list.add(u);
        }
        return list;
    }

    /**
     * 测试poi工具类
     * @param response
     * @throws Exception
     */
    @GetMapping("testPoi")
    public void testPoi(HttpServletResponse response) throws Exception {
        List<Map<String,String>> titleList=new ArrayList<>();
        Map<String,String> titleMap=new HashMap<String,String>();
        titleMap.put("id","11");titleMap.put("pid","0");titleMap.put("content","登录名");titleMap.put("fielName","u_login_id");
        Map<String,String> titleMap1=new HashMap<String,String>();
        titleMap1.put("id","1");titleMap1.put("pid","0");titleMap1.put("content","姓名");titleMap1.put("fielName","u_name");
        Map<String,String> titleMap2=new HashMap<String,String>();
        titleMap2.put("id","2");titleMap2.put("pid","0");titleMap2.put("content","角色加部门");titleMap2.put("fielName",null);
        Map<String,String> titleMap3=new HashMap<String,String>();
        titleMap3.put("id","3");titleMap3.put("pid","2");titleMap3.put("content","角色");titleMap3.put("fielName","u_role");
        Map<String,String> titleMap4=new HashMap<String,String>();
        titleMap4.put("id","4");titleMap4.put("pid","2");titleMap4.put("content","部门");titleMap4.put("fielName","u_dep");
        Map<String,String> titleMap5=new HashMap<String,String>();
        titleMap5.put("id","22");titleMap5.put("pid","0");titleMap5.put("content","角色加部门1");titleMap5.put("fielName",null);
        Map<String,String> titleMap6=new HashMap<String,String>();
        titleMap6.put("id","22_1");titleMap6.put("pid","22");titleMap6.put("content","角色1");titleMap6.put("fielName","u_role");
        Map<String,String> titleMap7=new HashMap<String,String>();
        titleMap7.put("id","22_2");titleMap7.put("pid","22");titleMap7.put("content","部门1");titleMap7.put("fielName","u_dep");
        titleList.add(titleMap); titleList.add(titleMap1); titleList.add(titleMap2); titleList.add(titleMap3); titleList.add(titleMap4);
        titleList.add(titleMap5); titleList.add(titleMap6); titleList.add(titleMap7);
        // 单级的 行内数据
        List<Map<String,String>> rowList=new ArrayList<>();
        for(int i=0;i<7;i++){
            Map m= new HashMap<String,String>();
            m.put("u_login_id","登录名"+i); m.put("u_name","张三"+i);
            m.put("u_role","角色"+i); m.put("u_dep","部门"+i);
            m.put("u_type","用户类型"+i);
            rowList.add(m);
        }
        ExcelTool excelTool = new ExcelTool("List<Map>数据 多级表头表格",20,20);
        List<Column>  titleData=excelTool.columnTransformer(titleList,"id","pid","content","fielName","0");
        // excelTool.exportExcel(titleData,rowList,"D://outExcel2.xls",true,false);
        excelTool.exportExcelResponse(titleData,rowList,response,true,false);
    }
}
